<?

require_once("mysql.php");
require_once("session.php");

SESSION();

function build_facebook_friends_list() {

	$userid = $_SESSION['userid'];
	$token  = $_SESSION['token'];

    $q = "https://graph.facebook.com/".$userid."/friends?access_token=".$token;
	$t = "";
	
	$friends = json_decode(@file_get_contents($q), TRUE);
	
	foreach ($friends['data'] as $friend) {
	    $t = $t."id=".$friend['id']." OR ";
	}
	$t = $t."id=0"; // Terminate the last OR with a junk check
	
	// Build a list of users that are in the app DB who are friends of this user
	$q = "SELECT id FROM user WHERE (XXX)";
	$q = str_replace('XXX', $t, $q);
	$r = MYSQL_Q($q);
	$c = mysql_num_rows($r);
	
    // Delete all entries for this user from the friends DB
	$q = "DELETE FROM friend WHERE userid=XXX";
	$q = str_replace("XXX", $userid, $q);
	MYSQL_Q($q);	

    // If no friends are found in the app DB... no-op
	if ($c == 0) return;
	
	$t = ""; $i = 0;
	while($friend = mysql_fetch_assoc($r)) {
	    $t = $t."(".$userid.",".$friend['id'].")".(++$i == $c ? ";" : ",");
    }
	
	// Insert (user->friend) mappings back into the friend DB
    $q = "INSERT INTO friend VALUES XXX";
	$q = str_replace("XXX", $t, $q);
	MYSQL_Q($q);
}

?>